package com.wzy.rabbitmqapi.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1创建一个ConnectionFactory,用于创建mq的物理链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/test");
        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.创建一个Channel;
        Channel channel = connection.createChannel();
        channel.queueDeclare("helloworld", false, false, false, null);
        //如果不屑这个规则,那么rabbit会使用默认策略,平均发送给消费者
        //设置为 1 ,mq不再对消费者一次性发送多个请求,而是消费者处理完一个消息(确认后) ,再去队列自己获取一个新的
        channel.basicQos(1);
        //创建一个消息消费者
        //第二个参数代表是否自动确认收到的消息,false代表手动
        //第三个参数 实现了DefaultConsumer的消费者对象
        channel.basicConsume("helloworld", false, new MyConsumer(channel));





//        String exchangeName = "test_consumer_exchange";
//        String routingKey = "consumer.#";
//        String queueName = "test_consumer_queue";
//        //声明一个交换机
//        channel.exchangeDeclare(exchangeName, "topic", true, false, null);
//        //4.声明一个队列
//
//        //交换机和队列,绑定路由键
//        channel.queueBind(queueName, exchangeName, routingKey);
//
//        channel.basicConsume(queueName, true, new MyConsumer(channel));
    }
}
